package cn.backflow.admin.common.secure;

import cn.backflow.admin.common.interceptor.UnauthorizedException;
import cn.backflow.lib.util.WebUtil;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.annotation.Annotation;
import java.util.List;

/**
 * 拦截@Permission注解的方法进行权限验证
 * <p>
 * Created by hunan on 2017/5/21.
 */
@Component
public class PermissionInterceptor extends HandlerInterceptorAdapter {

    private static Logger logger = LoggerFactory.getLogger(PermissionInterceptor.class);
    private final RedisTemplate<String, String> redisTemplate;

    @Autowired
    public PermissionInterceptor(RedisTemplate<String, String> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String info = request.getMethod() + " : " + request.getRequestURI();
        logger.info(info);

        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Permissions permission = getAnnotation(handlerMethod, Permissions.class);
            if (permission == null) {
                return true;
            }
            boolean authorized = checkPermission(permission.value(), request);
            if (!authorized) {
                logger.info("Unauthorized request: {}", info);
                JSONObject json = new JSONObject();
                json.put("msg", "Unauthorized.");
                response.setStatus(401);
                response.setContentType("application/json; charset=UTF-8");
                response.getWriter().write(json.toString());
                return false;
            }
        }
        return true;
    }


    @SuppressWarnings("unchecked")
    public boolean checkPermission(final String permission, HttpServletRequest request) throws Exception {
        // TODO add redis implementation
        // User user = (User) request.getSession().getAttribute(Constants.SESSION_USER_KEY);
        // Set<String> permissions = redisTemplate.opsForSet().members("");

        List<String> permissions = (List<String>) request.getSession().getAttribute("permissions");
        if (permissions == null || !permissions.contains(permission)) {
            logger.info("Unauthorized request: " + permission);
            throw new UnauthorizedException("Unauthorized.");
        }
        return true;
    }

    private <T extends Annotation> T getAnnotation(HandlerMethod handlerMethod, Class<T> clazz) {
        T annotation = handlerMethod.getMethodAnnotation(clazz);
        if (annotation != null) {
            return annotation;
        }
        return AnnotationUtils.findAnnotation(handlerMethod.getBeanType(), clazz);
    }
}